<template>
    <div class="area-select">
        <popup :open.sync="show" @confirm="confirm" @cancel="cancel" :title="title" :mask="mask" :showHeader="showHeader">
            <div class="date-title">
                <ul>
                    <li>年</li>
                    <li>月</li>
                    <li>日</li>
                    <template v-if="type === 'datetime' || type === 'time'">
                        <li>时</li>
                        <li>分</li>
                    </template>
                    <template v-if="type === 'time'">
                        <li>秒</li>
                    </template>
                </ul>
            </div>
            <div class="wheel">
                <brsSelect :list="year_list" :defaultIndex="selectIndex[0]" @change="changeHandle($event, 0)"></brsSelect>
                <brsSelect :list="month_list" :defaultIndex="selectIndex[1]" @change="changeHandle($event, 1)"></brsSelect>
                <brsSelect :list="day_list" :defaultIndex="selectIndex[2]" @change="changeHandle($event, 2)"></brsSelect>
                <template v-if="type === 'datetime' || type === 'time'">
                    <brsSelect :list="hour_list" :defaultIndex="selectIndex[3]" @change="changeHandle($event, 3)"></brsSelect>
                    <brsSelect :list="minute_list" :defaultIndex="selectIndex[4]" @change="changeHandle($event, 4)"></brsSelect>
                </template>
                <template v-if="type === 'time'">
                    <brsSelect :list="second_list" :defaultIndex="selectIndex[5]" @change="changeHandle($event, 5)"></brsSelect>
                </template>
            </div>
        </popup>
    </div>
</template>

<script>
import popup from "@/components/popup"
import brsSelect from "@/components/select"

export default {
    name: 'date-select',
    props: {
        open: {
            type: Boolean,
            default: false
        }, // 是否显示 date-select
        value: {
            type: [String, Number],
            default(){
                return 0
            }
        }, // 默认值 String：2020-12-25 14:00:00 Number：时间戳（毫秒）
        prefix: {
            type: Number,
            default: 30
        }, // 30 - 当前年份 + 30
        type: {
            type: String,
            validator(){
                // date：年月日， datetime：年月日时分， time：年月日时分秒
                return ['date', 'datetime', 'time']
            },
            default: 'time'
        },
        mask: {
            type: Boolean,
            default: true
        },
        showHeader: {
            type: Boolean,
            default: true
        },
        title: {
            type: String,
            default: ''
        }
    },
    components: { popup, brsSelect },
    data(){
        return {
            year_list: [],
            month_list: [],
            day_list: [],
            hour_list: [],
            minute_list: [],
            second_list: [],
            selectIndex: [0, 0, 0, 0, 0, 0], // 默认选中的index
            show: false, // 是否显示 popup
        }
    },
    watch: {
        open(val){
            this.show = val
            if(val){
                this.$nextTick(() => {
                    this.initData()
                })
            }
        }
    },
    methods: {
        cancel(){
            this.show = false;
            this.$emit('update:open', false);
            this.$emit('cancel');
        },
        confirm(){
            let year = this.year_list.filter((el, index) => index === this.selectIndex[0])[0].id
            let month = this.month_list.filter((el, index) => index === this.selectIndex[1])[0].id
            let day = this.day_list.filter((el, index) => index === this.selectIndex[2])[0].id
            let hour = this.hour_list.filter((el, index) => index === this.selectIndex[3])[0].id
            let minute = this.minute_list.filter((el, index) => index === this.selectIndex[4])[0].id
            let second = this.second_list.filter((el, index) => index === this.selectIndex[5])[0].id
            let datetime = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
            this.show = false;
            this.$emit('update:open', false);
            this.$emit('confirm', {year, month, day, hour, minute, second, datetime});
        },
        /**
         * 初始化默认值
         */
        async initData(){
            let nowDate = new Date();
            if(this.value){
                try {
                    nowDate = new Date(this.value);
                } catch (error) {
                    nowDate = new Date();
                }
            }
            let dateInfo = this.getDateInfo(nowDate)
            let year = Number(dateInfo.year)
            let l = [], m = [ {id: dateInfo.year, title: dateInfo.year} ], r = [] 
            for (let index = 1; index <= this.prefix; index++) {
                l.push({id: String(year-index), title: String(year-index)})
                r.push({id: String(year+index), title: String(year+index)})
            }
            this.year_list = [...l.reverse(), ...m, ...r];
            this.month_list = this.buildData(12);
            this.day_list = this._getDayList(this.year_list[this.selectIndex[0]].id, this.month_list[this.selectIndex[1]].id);
            this.hour_list = this.buildData(23);
            this.minute_list = this.buildData(59);
            this.second_list = this.buildData(59);

            this.$set(this.selectIndex, 0, this.getSelectIndex(this.year_list, dateInfo.year));
            this.$set(this.selectIndex, 1, this.getSelectIndex(this.month_list, dateInfo.month));
            this.$set(this.selectIndex, 2, this.getSelectIndex(this.day_list, dateInfo.day));
            this.$set(this.selectIndex, 3, this.getSelectIndex(this.hour_list, dateInfo.hour));
            this.$set(this.selectIndex, 4, this.getSelectIndex(this.minute_list, dateInfo.minute));
            this.$set(this.selectIndex, 5, this.getSelectIndex(this.second_list, dateInfo.second));

        },
        buildData(num){
            let list = []
            for (let index = 1; index <= num; index++) {
                let text = String(index);
                if(index < 10){
                    text = '0' + index;
                }
                list.push({id: text, title: text})
            }
            return list;
        },
        /**
         * 获取当前月的天数
         *
         * @param   {Number}  year   年份
         * @param   {Number}  month  月份
         *
         * @return  {Number} 天数
         */
        _getTotalDay(year, month){
            year = Number(year);
            month = Number(month);
            return new Date(year, month, 0).getDate()
        },
        _getDayList(year, month){
            return this.buildData(this._getTotalDay(year, month))
        },
        /**
         * 获取code的index
         *
         * @param   {Array}  array  需要循环的数组
         * @param   {String}  code  
         *
         * @return  {Number} index值
         */
        getSelectIndex(array, code){
            let returnIndex = null;
            for (let index = 0; index < array.length; index++) {
                const element = array[index];
                if(element.id === code){
                    returnIndex = index;
                    break;
                }
            }
            return returnIndex;
        },
        getDateInfo(date){
            return {
                year: String(date.getFullYear()),
                month: date.getMonth() < 9 ? String('0' + date.getMonth() +1) : String(date.getMonth() + 1),
                day: date.getDate() < 10 ? String('0' + date.getDate()) : String(date.getDate()),
                hour: date.getHours() < 10 ? String('0' + date.getHours()) : String(date.getHours()),
                minute: date.getMinutes() < 10 ? String('0' + date.getMinutes()) : String(date.getMinutes()),
                second: date.getSeconds() < 10 ? String('0' + date.getSeconds()) : String(date.getSeconds())
            }
        },
        changeHandle(event, index){
            this.$set(this.selectIndex, index, event)
        }
    }
}
</script>

<style lang="less" scoped>
.date-title{
    padding-top: 30px;
    ul{
        display: flex;
        li{
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    }
}
.wheel{
    display: flex;
    /deep/ .brs-select{
        flex: 1;
    }
}
</style>